import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wk_weather/bean/EnventChangeBean.dart';
import 'package:wk_weather/bean/CityInfo.dart';
import 'package:wk_weather/myconfig/ViewState.dart';
import 'package:wk_weather/utils/MyLogTool.dart';
import 'package:wk_weather/bloc/city/city_bloc.dart';
import 'package:wk_weather/views/MyApp.dart';
import 'package:wk_weather/views/widget/StateView.dart';
import 'package:wk_weather/views/pages/home/CityView.dart';

// todo 主页详情页
class MainMessage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MainMessageState();
  }
}

class _MainMessageState extends State<MainMessage> {
  List<CityModel> _cityModels;
  PageController _controller = PageController();
  StreamSubscription _subscription;

  Widget _buildMainWidget() {
    if (_cityModels == null) {
      weatherPrint("_cityModels 为 null");
      return StateView(weatherState: ViewState.loading);
    } else if (_cityModels.isEmpty) {
      weatherPrint("_cityModels 为  Empty");
      return StateView(weatherState: ViewState.empty);
    } else {

      _cityModels.forEach((element) {
        weatherPrint('\r\n关注的城市信息: $element');
      });

      return PageView.builder(
        controller: _controller,
        onPageChanged: (index) {
          eventBus.fire(ChangeMainAppBarIndexEvent(index, _cityModels[index].cityFlag));
        },
        itemBuilder: (context, index) {
          return CityView(
            cityModel: _cityModels[index],
          );
        },
        itemCount: _cityModels.length,
      );
    }
  }

  @override
  void initState() {
    _subscription = eventBus.on<ChangeCityEvent>().listen((event) {
      if (_cityModels != null) {
        _cityModels.forEach((element) {
          if (element.cityFlag == event.cityFlag) {
            var index = _cityModels.indexOf(element);
            if (index >= 0 && index < _cityModels.length) {
              _controller.jumpToPage(index);
            }
          }
        });
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var state = BlocProvider.of<CityBloc>(context).state;
    weatherPrint('主页面 城市当前状态: ${state.runtimeType}');
    if (state is CitySuccess) {
      weatherPrint("_cityModels 被赋值 -- >  state is CitySuccess") ;
      _cityModels = state.cityModels;
    }
    return BlocListener<CityBloc, CityState>(
      listener: (_, state) {
        weatherPrint('BlocListener 监听到状态改变: ${state.runtimeType}');
        if (state is CitySuccess) {
          setState(() {
            _cityModels = state.cityModels;
            weatherPrint("_cityModels 被赋值 -- >   BlocListener") ;
          });
        }
      },
      child: _buildMainWidget(),
    );
  }
}
